package com.star.basedemo.controller;

import com.star.basedemo.bean.Student;
import com.star.basedemo.config.DBContextHolder;
import com.star.basedemo.response.BaseResponse;
import com.star.basedemo.service.DBChangeService;
import com.star.basedemo.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.List;

@RestController
@RequestMapping("/student")
@Slf4j
public class StudentController {
    @Autowired
    private StudentService studentService;

    @Autowired
    private DBChangeService dbChangeServiceImpl;
    /**
     * 查询所有
     * @return
     */
    @GetMapping("/test")
    public  String test() throws Exception {

        //切换到数据库dbtest1
        String datasourceId="dbtest1";
        dbChangeServiceImpl.changeDb(datasourceId);
        List<Student> userList= studentService.all1();
        System.out.println(userList.toString());

        //再切换到数据库dbtest2
        dbChangeServiceImpl.changeDb("dbtest2");
        List<Student> userList3= studentService.all1();
        System.out.println(userList3.toString());


        //切回主数据源
        DBContextHolder.clearDataSource();
        return "ok";
    }

    @PostMapping("all1")
    public List<Student> studentAll() {
        log.info("进入成功！！！");
        return studentService.all1();
    }
    @PostMapping("all2")
    public List<Student> studentAll2() {
        log.info("进入成功！！！");
        return studentService.all1();
    }

    @DeleteMapping("/del/{id}")
    public BaseResponse<Student> studentDel(@PathVariable Integer id) {
        log.info("删除成功！！！id={}", id);
        return studentService.del(id) > 0
                ? new BaseResponse<Student>(200, "删除成功")
                : new BaseResponse<Student>(500, "删除失败");
    }

    @PostMapping("/insert")
    public BaseResponse<Student> studentInsert(Student stu) {
        log.info("添加成功!!!stu={}", stu);
        return studentService.save(stu) > 0
                ? new BaseResponse<Student>(200, "添加成功")
                : new BaseResponse<Student>(500, "添加失败");
    }

    @PostMapping("/update")
    public BaseResponse<Student> studentUpdate(Student stu){
        log.info("修改成功!!!stu={}",stu);
        return studentService.update(stu) > 0
                ? new BaseResponse<Student>(200, "添加成功")
                : new BaseResponse<Student>(500, "添加失败");
    }

}
